/*
 * Powered By xTOOLs
 * Dev by DuRisk@pactera.com
 * Copyright © 2009 - 2018 pactera.com. All rights reserved.
 *
 * Generated at 2018年02月28日 22:36:01
 *
 */

package com.pactera.jep.service.sys.web.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.alibaba.fastjson.JSONObject;
import com.pactera.jep.sys.code.StaffType1;
import com.pactera.jep.sys.model.Staff;
import com.pactera.jep.sys.service.StaffService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import com.pactera.jep.autoconfigure.web.controller.BaseRestController;
import com.pactera.jep.core.code.Status;
import com.pactera.jep.core.context.Context;
import com.pactera.jep.core.context.IdentityContext;
import com.pactera.jep.core.exception.ServiceException;
import com.pactera.jep.orm.Filter;
import com.pactera.jep.orm.Order;
import com.pactera.jep.orm.Page;
import com.pactera.jep.service.sys.service.UserProfileService;
import com.pactera.jep.sys.dto.StaffDto;
import com.pactera.jep.sys.model.Tenant;
import com.pactera.jep.sys.service.TenantService;
import com.pactera.jep.web.code.WebCode;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@Api(tags = "租户管理")
@RestController
@RequestMapping("/tenant")
public class TenantRestController extends BaseRestController<Tenant> {
    private static Logger logger = LoggerFactory.getLogger(TenantRestController.class);

    @Autowired
    private TenantService tenantService;

    @Autowired
    private StaffService staffService;

    @Autowired
    private UserProfileService userProfileService;

    /**
     * 为列表页面做数据准备
     */
    @Override
    protected void prepareQuery(String token, Page<Tenant> page, List<Filter> filters, List<Order> orders,
                                HttpServletRequest request) {
        tenantService.query(page, filters, orders);
    }

    @ApiOperation(value = "保存租户信息")
    @PostMapping(value = "/save")
    public Map<String, Object> save(@RequestBody Tenant tenant) {
        Map<String, Object> tips = new HashMap<String, Object>();

        // 修改context中tenantRequired为 false
        IdentityContext context = Context.getIdentityContext();
        context.setTenantRequired(false);

        // 更新和保存只操作租户表
        Boolean isExist = tenantService.exists(tenant.getId());
        try {
            if (isExist) {
                tenantService.update(tenant);
            } else {
                tenant.setStatus(Status.DRAFT.getValue());
                tenantService.insert(tenant);
            }
            tips.put(WebCode.SUCCESS, true);
            tips.put(WebCode.MSG, WebCode.SUCCESS_SAVE);

        } catch (ServiceException e) {
            logger.info(e.getMessage());
            tips.put(WebCode.SUCCESS, false);
            tips.put(WebCode.MSG, WebCode.FAILURE_SAVE);
        }
        return tips;
    }

    @ApiOperation(value = "根据id删除")
    @DeleteMapping(value = "/remove/{id}")
    public Map<String, Object> remove(@PathVariable String id) {
        Map<String, Object> tips = new HashMap<String, Object>();
        try {
            tenantService.deleteTenant(id);
            tips.put(WebCode.SUCCESS, true);
            tips.put(WebCode.MSG, WebCode.SUCCESS_DELETE);
        } catch (ServiceException e) {
            logger.info(e.getMessage());
            tips.put(WebCode.SUCCESS, false);
            tips.put(WebCode.MSG, WebCode.FAILURE_DELETE);
        }
        return tips;
    }

    @ApiOperation(value = "查询所有租户")
    @PostMapping(value = "/queryList")
    public List<Tenant> queryList(@RequestBody Model model) {
        List<Tenant> tenants = tenantService
                .select(new Filter.Builder().eq("status", Status.ENABLED.getValue()).build());
        return tenants;
    }

    @ApiOperation(value = "启动租户")
    @PostMapping(value = "/start/{id}")
    public Map<String, Object> start(@PathVariable String id) {
        Map<String, Object> tips = new HashMap<String, Object>();
        try {

            //启动时，存入管理用户，和机构信息
            Tenant tenant = tenantService.get(id);
            userProfileService.insertStaffAdm(tenant);

            tips.put(WebCode.SUCCESS, true);
            tips.put(WebCode.MSG, WebCode.SUCCESS_OPERATE);
        } catch (ServiceException e) {
            logger.info(e.getMessage());
            tips.put(WebCode.SUCCESS, false);
            tips.put(WebCode.MSG, WebCode.FAILURE_OPERATE);
        }
        return tips;
    }

    @ApiOperation(value = "停止租户")
    @PostMapping(value = "/stop/{id}")
    public Map<String, Object> stop(@PathVariable String id) {
        Map<String, Object> tips = new HashMap<String, Object>();
        try {
            Tenant tenant = tenantService.get(id);
            tenant.setStatus(Status.DISABLED.getValue());
            tenantService.update(tenant);
            tips.put(WebCode.SUCCESS, true);
            tips.put(WebCode.MSG, WebCode.SUCCESS_OPERATE);
        } catch (ServiceException e) {
            logger.info(e.getMessage());
            tips.put(WebCode.SUCCESS, false);
            tips.put(WebCode.MSG, WebCode.FAILURE_OPERATE);
        }
        return tips;
    }

    @ApiOperation(value = "验证提交的code是否已经存在数据库中")
    @GetMapping(value = "/check", produces = "application/json;charset=UTF-8")
    public Map<String, Object> check(String name, String value) {
        Map<String, Object> tips = new HashMap<String, Object>();
        List<Tenant> list = tenantService.select(new Filter.Builder().eq(name, value).build());
        if (list.size() > 0)
            tips.put("valid", false);
        else
            tips.put("valid", true);
        return tips;
    }
}
